/**
 * https://leetcode.cn/problems/longest-harmonious-subsequence/
 */
function findLHS(nums: number[]): number {
  let ans = 0;
  const map = new Map();

  // 1. 计算数量
  nums.forEach((num) => {
    map.set(num, (map.get(num) || 0) + 1);
  });

  // 2. 计算最大值
  map.forEach((count, num) => {
    // 假设 num 下一个有值
    const nextCount = map.get(num + 1);
    if (nextCount !== undefined) {
      ans = Math.max(nextCount + count, ans);
    }
  });

  return ans;
}

function findLHS2(nums: number[]): number {
  let ans = 0;

  nums.sort((a, b) => a - b);

  let index = 0;
  let prev = 0;
  const arr = [0];
  while (index < nums.length) {
    if (nums[index] !== nums[prev]) {
      prev = index;
      arr.push(index);
    }
    index++;
  }
  arr.push(nums.length);
  for (let i = 1; i < arr.length; i++) {
    if (nums[arr[i]] - nums[arr[i - 1]] === 1 && i + 1 < arr.length) {
      ans = Math.max(ans, arr[i + 1] - arr[i - 1]);
    }
  }

  return ans;
}

// 数组解题思路
// 1. 排序
// 2. 指针
// 3. map 数据结构辅助
// 4. 螺旋矩阵索引的转换，即取模的灵活运用
